package top.wshape1.shiziapi.search.controller;

import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import top.wshape1.shiziapi.common.domain.ProjectSearch;
import top.wshape1.shiziapi.common.domain.to.DateGapTo;
import top.wshape1.shiziapi.common.utils.R;
import top.wshape1.shiziapi.search.domain.ProjectSearchPage;
import top.wshape1.shiziapi.search.service.ProjectSearchService;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2023-11-20
 */

@RestController
@RequestMapping("/elastic")
public class ElasticController {

    @Resource
    private ProjectSearchService projectSearchService;

    @PostMapping("/save")
    public R<Void> save(@RequestBody ProjectSearch project) throws IOException {

        projectSearchService.save(project);

        return R.ok();
    }

    @PostMapping("/remove")
    public R<Void> remove(@RequestParam("id") Long id) throws IOException {

        projectSearchService.remove(id);

        return R.ok();
    }

    @PostMapping("/like")
    public R<Void> like(@RequestParam("count") Long count, @RequestParam("id") Long id) throws IOException {

        projectSearchService.setLike(id, count);

        return R.ok();
    }

    @PostMapping("/like/{plusOrReduce}")
    public R<Void> likePlusOrReduce(@PathVariable("plusOrReduce") String plusOrReduce, @RequestParam("id") Long id) throws IOException {

        projectSearchService.plusOrReduceLike(id, plusOrReduce, new Date());

        return R.ok();
    }

    @PostMapping("/count/read")
    public R<Long> countRead(@RequestParam("projectId") Long projectId) throws IOException {
        return R.ok(projectSearchService.getByProjectId(projectId).getReadCount());
    }

    @PostMapping("/read/list")
    public R<List<ProjectSearch>> readList(@RequestBody DateGapTo to) throws IOException {
        return R.ok(
                projectSearchService.getProjectBetweenUpdateTime(to.getStartTime(), to.getEndTime())
                        .stream()
                        .map(projectSearch -> {
                            ProjectSearch search = new ProjectSearch();
                            search.setId(projectSearch.getId());
                            search.setReadCount(projectSearch.getReadCount());
                            search.setUpdateTime(projectSearch.getUpdateTime());
                            return search;
                        })
                        .toList()
        );
    }

    @PostMapping("/project/hot")
    public R<List<ProjectSearch>> hot() throws IOException {
        return R.ok(projectSearchService.getHotProjects(1).getProjectSearchList());
    }

}
